package com.food.restaurantpro.database;

import com.food.restaurantpro.database.tables.DishCategoryTable;
import com.food.restaurantpro.database.tables.FoodTable;
import com.food.restaurantpro.database.tables.PlaceTable;
import com.food.restaurantpro.database.tables.PromotionTable;
import com.food.restaurantpro.database.tables.ReservationTable;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {

	public static final String DB_NAME = "restaurantprodb.db";
	public static final int DB_VERSION = 1;
	public static final String[] TABLE_NAMES = new String[] { PromotionTable.TABLE_NAME, DishCategoryTable.TABLE_NAME, FoodTable.TABLE_NAME, PlaceTable.TABLE_NAME, ReservationTable.TABLE_NAME };
	public static final String[] SQL_EXCUTE = new String[] { PromotionTable.SQL_EXCUTE, DishCategoryTable.SQL_EXCUTE, FoodTable.SQL_EXCUTE, PlaceTable.SQL_EXCUTE, ReservationTable.SQL_EXCUTE };

	public DatabaseHelper(Context context) {
		super(context, DB_NAME, null, DB_VERSION);

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		try {
			dropMultipleSQL(db, TABLE_NAMES);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		this.onCreate(db);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.beginTransaction();
		try {
			execMultipleSQL(db, SQL_EXCUTE);
			db.setTransactionSuccessful();
		} catch (android.database.SQLException e) {
			throw e;
		} finally {
			db.endTransaction();
		}
		// -------------------------
	}

	private void execMultipleSQL(SQLiteDatabase db, String[] sql)
			throws android.database.SQLException {
		for (String s : sql) {
			if (s.trim().length() > 0) {
				try {
					db.execSQL(s);
				} catch (android.database.SQLException e) {
					throw new android.database.SQLException();
				}
			}
		}
	}

	private void dropMultipleSQL(SQLiteDatabase db, String[] tablename)
			throws android.database.SQLException {
		for (String s : tablename) {
			if (s.trim().length() > 0) {
				try {
					db.execSQL("DROP TABLE IF EXISTS " + s + ";");
				} catch (android.database.SQLException e) {
					throw new android.database.SQLException();
				}
			}
		}
	}
}
